package com.gz.mylife.app;

import java.lang.ref.WeakReference;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.listener.CheckPhoneNumber;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Register1 extends BaseActivity implements OnClickListener {
	private EditText mEtNumber;
	private Button mBtnRegister;
	private Dialog mLoadingData;
	private TextView mTvLoading;
	private MyCheckListener mListener;
	private int type;
	private AlertDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register1);
		initView();
		type = getIntent().getIntExtra("type", 0);
		if(type == 0){
			setActionbarTitle("新账号", false);
			mEtNumber.setHint("请输入您的手机号");
			mBtnRegister.setText("注册账号");
			createDialog();
		}else{
			setActionbarTitle("密码找回", false);
			mEtNumber.setHint("请输入您绑定的手机号");
			mBtnRegister.setText("重设密码");
		}

	}

	public void initView() {
		mListener = new MyCheckListener(this);
		mLoadingData = new Dialog(this, R.style.DialogTheme);
		View loadView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.loading_data_dialog2, null);
		mLoadingData.setContentView(loadView);
		mTvLoading = (TextView) loadView.findViewById(R.id.show_tv);
		mTvLoading.setText("验证码发送中");
		mLoadingData.setCanceledOnTouchOutside(true);
		mEtNumber = (EditText) findViewById(R.id.et_phone_number);
		mEtNumber.addTextChangedListener(myWatcher);
		mBtnRegister = (Button) findViewById(R.id.btn_register);
		mBtnRegister.setOnClickListener(this);
		mBtnRegister.setBackgroundResource(R.drawable.register_btn_default);
		mBtnRegister.setClickable(false);
	}

	private TextWatcher myWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			String str = s.toString();
			if (!TextUtils.isEmpty(str)) {
				mBtnRegister
				.setBackgroundResource(R.drawable.selector_register_btn);
				mBtnRegister.setClickable(true);
			} else {
				mBtnRegister
				.setBackgroundResource(R.drawable.register_btn_default);
				mBtnRegister.setClickable(false);
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_register:
			//			startActivity(new Intent(getApplicationContext(), Register3.class));
			mLoadingData.show();
			switch (type) {
			case 0:
				loadDataFromSever();
				break;
			default:
				forgetPassword();
				break;
			}
			break;

		default:
			break;
		}
	}

	private void forgetPassword() {
		if (!Tools.hasInternetConnection(getApplicationContext())) {
			mLoadingData.dismiss();
			Toast.makeText(this, Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT)
			.show();
			return;
		}
		String url = Constants.URL_GET_PASSWORD;
		RequestParams params = new RequestParams();
		params.put("phone", mEtNumber.getText().toString());
		mListener.setmReqType(CheckPhoneNumber.GET_RESETPASSWORD_SMSCODE);
		SingtonAsyncHttpClient.getInstance().post(url, params, mListener);
	}

	private void loadDataFromSever() {
		if (!Tools.hasInternetConnection(getApplicationContext())) {
			mLoadingData.dismiss();
			Toast.makeText(this, Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT)
			.show();
			return;
		}
		String url = Constants.URL_CHECK_PHOME;
		RequestParams params = new RequestParams();
		params.put("phone", mEtNumber.getText().toString());
		mListener.setmReqType(CheckPhoneNumber.CHECK_PHONE_NUMBER);
		SingtonAsyncHttpClient.getInstance().post(url, params, mListener);//注册请求验证码
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mListener.release();
	}

	private static class MyCheckListener extends CheckPhoneNumber {
		private Register1 mOuter;

		public MyCheckListener(Register1 outer) {
			this.mOuter = outer;
		}

		public void release() {
			new WeakReference<Register1>(mOuter);
		}

		@Override
		public void onResponseSuccess(String phone, String smsCode) {
			if(mOuter == null){
				return;
			}
			Intent intent = new Intent(mOuter.getApplicationContext(), Register2.class);
			intent.putExtra("phone", phone); 
			intent.putExtra("smscode", smsCode);
			switch (mReqType) {
			case CheckPhoneNumber.CHECK_PHONE_NUMBER:
				CrashHandler.d("sms", smsCode);
				intent.putExtra("type", 0);
				break;
			case CheckPhoneNumber.GET_RESETPASSWORD_SMSCODE:
				CrashHandler.d("smspassword", smsCode);
				intent.putExtra("type", 1);
				break;
			default:
				break;
			}
			mOuter.startActivity(intent);
			mOuter.mLoadingData.dismiss();
		}

		@Override
		public void onPhoneError() {
			if(mOuter == null){
				return;
			}
			switch (mReqType) {
			case CheckPhoneNumber.CHECK_PHONE_NUMBER:
			case CheckPhoneNumber.GET_RESETPASSWORD_SMSCODE:
				mOuter.mLoadingData.dismiss();
				Toast.makeText(mOuter.getApplicationContext(), "您输入的手机号有误", 0).show();
				break;
			default:
				break;
			}
		}

		@Override
		public void onPhoneIsUsed() {
			if(mOuter == null){
				return;
			}

			switch (mReqType) {
			case CheckPhoneNumber.CHECK_PHONE_NUMBER:
				mOuter.mLoadingData.dismiss();
				Toast.makeText(mOuter.getApplicationContext(), "该手机号已注册", 0).show();
				break;
			case CheckPhoneNumber.GET_RESETPASSWORD_SMSCODE:
				mOuter.mLoadingData.dismiss();
				Toast.makeText(mOuter.getApplicationContext(), "该手机号未注册", 0).show();
				break;
			default:
				break;
			}
		}

		@Override
		public void onResponseFailed() {
			if(mOuter == null){
				return;
			}
			switch (mReqType) {
			case CheckPhoneNumber.CHECK_PHONE_NUMBER:
			case CheckPhoneNumber.GET_RESETPASSWORD_SMSCODE:
				mOuter.mLoadingData.dismiss();
				Toast.makeText(mOuter.getApplicationContext(), "网络请求失败", 0).show();
				break;

			default:
				break;
			}
		}

		@Override
		public void onNoNetWork() {
		}
		@Override
		public void passthree() {
			// TODO Auto-generated method stub
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "同一手机号当天发送验证码不能超过5次", 0).show();
		}

		@Override
		public void passtwo() {
			// TODO Auto-generated method stub
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "同一ip手机当天发送验证码不能超过10次", 0).show();
		}
	}
	//用户协议
	@SuppressLint("ResourceAsColor")
	private void createDialog() {
		dialog = new AlertDialog.Builder(Register1.this).create();
		View view = LayoutInflater.from(Register1.this).inflate(R.layout.activity_useragreement, null);
		dialog.setCanceledOnTouchOutside(false);//弹出框周围点击不起作用，返回键还起作用
		dialog.setView(view,0,0,0,0);
		dialog.show();
		DisplayMetrics metric = new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(metric);  
		int width = metric.widthPixels;     // 屏幕宽度（像素）  
		int height = metric.heightPixels;   // 屏幕高度（像素）  

		WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
		params.width = width-100;
		params.height = height-200;
		dialog.getWindow().setAttributes(params);
		final CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);
		final View line = view.findViewById(R.id.line1);
		final LinearLayout ly_agree = (LinearLayout) view.findViewById(R.id.ly_agree);
		WebView webview = (WebView) view.findViewById(R.id.webview); 
		WebSettings wv_setttig = webview.getSettings();
		wv_setttig.setJavaScriptEnabled(true);
		String url = "file:///android_asset/user_protocol.html";
		webview.loadUrl(url);

		view.findViewById(R.id.yesagree).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (checkbox.isChecked()) {
					dialog.dismiss();
				}else{
					Toast.makeText(Register1.this, "请勾选您同意此条款", Toast.LENGTH_LONG).show();
				}

			}
		});
		view.findViewById(R.id.noagree).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Register1.this,Login.class);
				startActivity(intent);
				finish();
			}
		});
		dialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub

				dialog.dismiss();
				finish();
			}
		});
	}
}
